#!/usr/bin/python3 -u
# -*- coding: utf-8 -*-

import sys
import os
import argparse
import json
import socket
import struct

import AutoExecUtils


def usage():
    # 帮助信息
    pname = os.path.basename(__file__)
    print(pname + "--masternode <master node json> --slavenodes <slave nodes json> --slaveinfo <slave server_id json> --myserverid <my server_id>")


if __name__ == "__main__":
    # 参数处理

    parser = argparse.ArgumentParser()
    parser.add_argument('--masternode', default='', help='master node')
    parser.add_argument('--slavenodes', default='', help='slave nodes')
    parser.add_argument('--slaveinfo', default='{}', help='slave info by show slave hosts')
    parser.add_argument('--myserverid', default='0', help='self possible server_id')

    args = parser.parse_args()

    hasOptError = 0
    if args.masternode == '':
        print("ERROR: Must defined master node by option --masternode")
        hasOptError = 1
    if args.slavenodes == '':
        print("ERROR: Must defined slave nodes by option --slavenodes")
        hasOptError = 1

    if hasOptError == 1:
        usage()

    exitCode = 0

    slaveInfo = json.loads(args.slaveinfo)
    myServerId = args.myserverid

    masterNodes = json.loads(args.masternode)
    slaveNodes = json.loads(args.slavenodes)

    existsServerIds = {}
    for slaveHost in slaveInfo:
        existServerId = slaveHost.get('Server_id')
        if existServerId is not None and existServerId != '':
            existsServerIds[existServerId] = 1

    myNode = AutoExecUtils.getMyNode()
    myIp = myNode.get('host')
    if myIp is None:
        myIp = myNode.get('ip')

    ipInt = None
    serverId = None
    if myServerId and myServerId != '0' and myServerId not in existsServerIds:
        serverId = myServerId
    else:
        allNodes = []
        allNodes.extend(masterNodes)
        allNodes.extend(slaveNodes)

        nodesCount = len(allNodes)
        for idx in range(1, nodesCount+1):
            node = allNodes[idx-1]
            nodeIp = node.get('ip')
            if nodeIp is None:
                nodeIp = node.get('host')

            if nodeIp == myIp:
                ipInt = struct.unpack('>L', socket.inet_aton(nodeIp))[0]
                # server_id的取值，取IP的后三个字节加上序号对256取模
                myIdx = idx
                serverId = ((ipInt & 0x00FFFFFF) << 8) | (myIdx % 256)

                while serverId in existsServerIds:
                    myIdx = myIdx + 1
                    serverId = ((ipInt & 0x00FFFFFF) << 8) | (myIdx % 256)

    out = {}

    if serverId is not None:
        print("INFO: Generate server_id:%s." % (serverId))
    else:
        exitCode = 1
        print("ERROR: Can not generate server_id.")

    out['server_id'] = serverId

    AutoExecUtils.saveOutput(out)

    sys.exit(exitCode)
